<?php
/**
 * Created by : PhpStorm
 * Index: 阿城 <479468212@qq.com>
 * Date: 2019/12/27
 * Time: 13:02
 */

namespace app\admin\controller\article;

use app\admin\controller\Base;
use app\common\model\CommonArticleCategory as categoryModel;
use think\exception\ValidateException;
use app\util\Tools;

class Category extends Base
{
    /**
     * @OA\Get(
     *   path="/admin/Article/categoryIndex",
     *   tags={"文章相关"},
     *   summary="文章分类列表",
     *   description="分类管理",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Response(
     *     response="200",
     *     description="返回JSON",
     *     @OA\MediaType(
     *      mediaType="application/json",
     *      @OA\Schema(
     *         @OA\Property(property="code", type="number",description="状态码"),
     *         @OA\Property(property="msg", type="string",description="提示消息"),
     *         @OA\Property(property="data", type="object",description="数据列表",@OA\Items),
     *      )
     *    )
     *   ),
     *   @OA\Response(response="500", description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function index()
    {
        $categoryModel= new categoryModel();
        $categoryList = $categoryModel->field('id,name as title,parent_id,parent_path,description,status')->order('id desc')->select()->toArray();
        $categoryTree = Tools::listToTree($categoryList,'id','parent_id','children');
        $this->success('获取文章分类成功',[ 'list' => $categoryTree ]);
    }

    /**
     * @OA\Post(
     *   path="/admin/Article/categoryAdd",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   tags={"文章相关"},
     *   summary="添加文章分类",
     *   @OA\RequestBody(
     *      @OA\MediaType(
     *         mediaType="application/json",
     *         @OA\Schema(
     *            @OA\Property(property="parent_id", type="string", description="父级ID"),
     *            @OA\Property(property="name", type="string", description="文章名称"),
     *            @OA\Property(property="description", type="string", description="描述"),
     *            @OA\Property(property="list_order", type="string", description="排序"),
     *            example={"parent_id":"0","name": "分类一", "description": "面朝大海，春暖花开","description":"从明天起，做一个幸福的人。面朝大海，春暖花开……","list_order":0}
     *         )
     *       )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="OK",
     *         @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *     ),
     *     @OA\Response(response="500", description="服务器错误"),
     *     security={{"App-Login-Token": ""}}
     * )
     */
    public function add() {
        $postData = $this->request->post();
        $validateRule =   [
            'name' => 'require'
        ];
        $validateMsg  =   [
            'name.require' => '名称必须'
        ];
        try {
            validate($validateRule,$validateMsg)->check($postData);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $categoryModel = new categoryModel();
        $find = $categoryModel->where(['name'=>$postData['name']])->find();
        if(!empty($find)){
            $this->error("分类重复");
        }
        if(intval($postData['parent_id']) > 0){
            $parent = $categoryModel->where(['id'=>$postData['parent_id']])->find();
            if(empty($parent)){
                $this->error("没有该父级分类");
            }
            $postData['parent_path'] = $parent['parent_path'].','.$parent['id'];
        }
        $result = $categoryModel->create($postData);
        if (!$result) {
            $this->error();
        }
        $this->success('成功');
    }

    /**
     * @OA\Post(
     *   path="/admin/Article/categoryEdit",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   tags={"文章相关"},
     *   summary="添加文章分类",
     *   @OA\RequestBody(
     *      @OA\MediaType(
     *         mediaType="application/json",
     *         @OA\Schema(
     *            @OA\Property(property="parent_id", type="string", description="父级ID"),
     *            @OA\Property(property="name", type="string", description="文章名称"),
     *            @OA\Property(property="description", type="string", description="描述"),
     *            @OA\Property(property="list_order", type="string", description="排序"),
     *            example={"parent_id":"0","name": "分类一", "description": "面朝大海，春暖花开","description":"从明天起，做一个幸福的人。面朝大海，春暖花开……","list_order":0}
     *         )
     *       )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="OK",
     *         @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *     ),
     *     @OA\Response(response="500", description="服务器错误"),
     *     security={{"App-Login-Token": ""}}
     * )
     */
    public function edit($id) {
        $postData = $this->request->post();
        $validateRule =   [
            'name' => 'require'
        ];
        $validateMsg  =   [
            'name.require' => '名称必须'
        ];
        try {
            validate($validateRule,$validateMsg)->check($postData);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $categoryModel = new categoryModel();
        $find = $categoryModel->where('id',$id)->find();
        if ($postData['parent_id'] != $find['parent_id'] && intval($postData['parent_id']) > 0) {
            $parent = $categoryModel->where(['id'=>$postData['parent_id']])->find();
            if (empty($parent)) {
                $this->error("没有该父级分类");
            }
            $postData['parent_path'] = $parent['parent_path'].','.$parent['id'];
        }
        $result = $find->save($postData);
        if (!$result) {
            $this->error();
        }
        $this->success('成功');
    }

    /**
     * @OA\Put(path="/admin/Article/changeCategoryStatus/{id}",
     *   tags={"文章相关"},
     *   summary="变更文章分类状态",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Parameter(name="id",in="path",required=true,description="分类ID",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Parameter(name="status",in="query",required=true,description="状态。0未发布，1已发布",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Response(
     *     response=200,
     *     description="返回Json",
     *     @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *   ),
     *   @OA\Response(response=500, description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function changeStatus($id) {
        $status = $this->request->param('status');
        if(!$id){
            $this->error('参数错误');
        }
        $res = categoryModel::update([
            'id'     => $id,
            'status' => $status
        ]);
        if ($res === false) {
            $this->error();
        } else {
            $this->success();
        }
    }

    /**
     * @OA\Delete(path="/admin/Article/categoryDelete/{id}",
     *   tags={"文章相关"},
     *   summary="删除文章分类",
     *   description="删除指定文章分类",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Parameter(name="id",in="path",required=true,description="分类ID",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Response(
     *     response=200,
     *     description="返回Json",
     *     @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *   ),
     *   @OA\Response(response=500, description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function delete($id) {
        if(!$id){
            $this->error('参数未填');
        }
        $categoryModel = new categoryModel();
        $subCategory = $categoryModel->where('parent_id',$id)->find();
        if(!empty($subCategory)){
            $this->error('请删除子分类后再操作');
        }
        $result = $categoryModel->destroy(['id'=>$id]);
        if(!$result){
            $this->error();
        }
        $this->success('成功');
    }
}
